#!/usr/bin/env/python3.7
# -*- coding: utf-8 -*-

"""
@File    : play_audio.py
@Time    : 11/30/2021
@Author  : Silence
@Version : 1.0
@Contact : silence2021silence@163.com
@License : (C)Copyright 2021-2021, Silence
@Desc    : None
"""

from __future__ import print_function
import sys
import wave
import getopt
import alsaaudio

def play(device, f):
    print('%d channels, %d sampling rate\n' % (f.getnchannels(),
                                               f.getframerate()))
    if f.getsampwidth() == 1:
        format = alsaaudio.PCM_FORMAT_U8
    elif f.getsampwidth() == 2:
        format = alsaaudio.PCM_FORMAT_S16_LE
    elif f.getsampwidth() == 3:
        format = alsaaudio.PCM_FORMAT_S24_LE
    elif f.getsampwidth() == 4:
        format = alsaaudio.PCM_FORMAT_S32_LE
    else:
        raise ValueError('Unsupported format')
    periodsize = f.getframerate() // 8
    device = alsaaudio.PCM(channels=f.getnchannels(), rate=f.getframerate(), format=format, periodsize=periodsize,
                           device=device)
    data = f.readframes(periodsize)
    while data:
        device.write(data)
        data = f.readframes(periodsize)

def usage():
    print('usage: playwav.py [-d <device>] <file>', file=sys.stderr)
    sys.exit(2)

if __name__ == '__main__':
    device = 'default'
    opts, args = getopt.getopt(sys.argv[1:], 'd:')
    for o, a in opts:
        if o == '-d':
            device = a
    if not args:
        usage()
    f = wave.open(args[0], 'rb')
    play(device, f)
    f.close()
